package cn.fintecher.pangolin.service.business.scheduled;

import cn.fintecher.pangolin.entity.elastic.CaseFollowupRecord;
import cn.fintecher.pangolin.entity.elastic.UploadFile;
import cn.fintecher.pangolin.service.business.repository.elasticsearch.CaseFollowRecordElastic;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : wangyannong
 * @Description :录音文件调度
 * @Date : 2019/12/4 9:44
 */
@EnableScheduling
@Component
public class RecordFileScheduled {
    private Logger log = LoggerFactory.getLogger(RecordFileScheduled.class);
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CaseFollowRecordElastic caseFollowRecordElastic;

    /**
     * 每日录音文件下载到文件服务器
     */
    @Scheduled(cron = "0 20 2 * * ?")
    public void getFile() {
        log.info("跟进记录录音更新任务调度开始...");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.existsQuery("url.keyword"));
        boolQueryBuilder.mustNot(QueryBuilders.existsQuery("record.id.keyword"));
        Iterable<CaseFollowupRecord> caseFollowupRecords = caseFollowRecordElastic.search(boolQueryBuilder);
        caseFollowupRecords.forEach(i -> {
            log.info("上传{}", i.getId());
            File file;
            try {
                String path = i.getUrl();
                file = new File(path);
                FileSystemResource resource = new FileSystemResource(file);
                MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
                param.add("file", resource);
                ResponseEntity<UploadFile> entity = restTemplate.postForEntity("http://common-service/api/uploadFile/upload", param, UploadFile.class);
                List<UploadFile> list = new ArrayList<>();
                if (entity.hasBody()) {
                    UploadFile uploadFile = entity.getBody();
                    list.add(uploadFile);
                    i.setRecord(list);
                }
                caseFollowRecordElastic.save(i);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                log.error("跟进记录录音更新任务调度错误,id为{}", i.getId());
            }
        });
        log.info("跟进记录录音更新任务调度结束");
    }
}
